/***************************************************************************
 *   Copyleft 2008-2009 by												   *
 *	 Iwanicki Krzysztof													   *
 *   <gamma.mini.pw.edu.pl/~iwanickik>									   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 ***************************************************************************/
#include "./vTexture2D.h"
//#include "../../Macros/vMacros.h"
#include <IL/il.h>
#include <IL/ilut.h>

namespace Vendetta {
	vTexture2D::vTexture2D() {
		mID = -1;
		mPath = "";
		mHeight = mWidth = 0;
	}

	vTexture2D::vTexture2D(const vString& fileName) {
		mPath = fileName;
		mID = -1;
		mHeight = mWidth = 0;
		if (!loadFromFile(fileName)) {
			throw vException("Image \"%s\" not loaded", fileName.ToConstCharPtr());
		}
	}

	vTexture2D::vTexture2D(const vTexture2D& texture2D) {
		mID = texture2D.mID;
		mWidth = texture2D.mWidth;
		mHeight = texture2D.mHeight;
		mPath = texture2D.mPath;
	}

	vTexture2D::~vTexture2D() {
		::glDeleteTextures(1, &mID);
	}

	vTexture2D& vTexture2D::operator=(const vTexture2D& texture2D) {
		if (this != &texture2D) {
			mID = texture2D.mID;
			mWidth = texture2D.mWidth;
			mHeight = texture2D.mHeight;
			mPath = texture2D.mPath;
		}

		return *this;
	}

	vUInt vTexture2D::ID() const {
		return mID;
	}

	const vString& vTexture2D::Path() const {
		return mPath;
	}

	vInt vTexture2D::Width() const {
		return mWidth;
	}

	vVoid vTexture2D::SetWidth(vInt val) {
		mWidth = val;
	}

	vInt vTexture2D::Height() const {
		return mHeight;
	}

	vVoid vTexture2D::SetHeight(vInt val) {
		mHeight = val;
	}

	vBool vTexture2D::loadFromFile(const vString& fileName) {
		ILuint imageID;
		ILboolean success;
		
		ilGenImages(1, &imageID);
		ilBindImage(imageID);
		ilutRenderer(ILUT_OPENGL);

		success = ilLoadImage(fileName.ToConstCharPtr());

		if (!success) {
			return false;
		}

		mWidth = ilGetInteger(IL_IMAGE_WIDTH);
		mHeight = ilGetInteger(IL_IMAGE_HEIGHT);
		mID = ilutGLBindTexImage();


		ilDeleteImages(1, &imageID);

		return true;
	}
}